# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re

from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.template.defaultfilters import truncatewords_html
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from wenlincms.utils.views import render
from wlapps.article.models import ArticlePost


@never_cache
def index(request):
    return render(request, "el_guan/index.html", {})


@never_cache
def join(request):
    return render(request, "el_guan/join.html", {})


@never_cache
def product(request):
    return render(request, "el_guan/product.html", {})


@never_cache
def solution(request):
    return render(request, "el_guan/solution.html", {})


@never_cache
@csrf_exempt
def news(request):
    result = {}

    # 默认
    # tab = request.GET.get('tab', '官方活动')
    pagenum = int(request.GET.get('pagenum', 1))
    pagesize = int(request.GET.get('pagesize', 5))
    findstr = request.GET.get('findstr', None)

    # 取得ajax查询参数
    if request.method == 'POST':
        # tab = request.POST.get('tab', '官方活动')
        pagenum = int(request.POST.get('pagenum', 1))
        pagesize = int(request.POST.get('pagesize', 5))
        findstr = request.POST.get('findstr','')

    result['findstr'] = findstr if findstr != 'None' else None
    # result['tab'] = tab
    result['pagenum'] = pagenum
    result['pagesize'] = pagesize

    # 查询
    news_list = ArticlePost.objects.all()
    if findstr and findstr != 'None':
        news_list = news_list.filter(title__contains=findstr)
    news_list = news_list.order_by('-id').values("id", "title", "content", "featured_image")
    count = len(news_list) / pagesize
    if len(news_list) % pagesize != 0:
        count += 1
    result['count'] = count
    centent = news_list[pagesize * (pagenum - 1):pagesize * pagenum]
    result['centent'] = centent

    # 截断html 去除img
    f = lambda x: truncatewords_html(x['content'], 10)
    for x in centent:
        html = f(x)
        if '<img' in html:
            html = re.sub('<img.*?>', '', html)
        x['content'] = html
    result = json.dumps(result)
    if request.method == 'POST':
        return HttpResponse(result)
    return render(request, "el_guan/news.html", {'result': result})


@never_cache
def about(request):
    return render(request, "el_guan/about.html", {})


@never_cache
def news_text(request):

    return render(request, "el_guan/news_text.html", {'result': result})
